import plugin from '../../lib/plugins/plugin.js';
import { segment } from "icqq";
import schedule from 'node-schedule';

export class RandomWifePlugin extends plugin {
    constructor() {
        super({
            name: '随机老婆',
            dsc: '每日随机群CP/结婚对象，支持拒绝功能',
            event: 'message',
            priority: 10,
            rule: [
                { // 随机匹配规则
                    reg: /^#(今日群?(老婆|对象|cp)|娶(群友|老婆|cp|对象)|jr(lp|cp|dx))$/i,
                    fnc: 'chooseWife'
                },
                { // 离婚功能
                    reg: /^#(离婚|lh)$/i,
                    fnc: 'handleDivorce'
                },
                { // 强娶功能
                    reg: /^#(强娶|qq)/i,
                    fnc: 'forceMarry'
                },
                { // 新增拒绝规则
                    reg: /^#(一键拒绝|解除拒绝)$/i,
                    fnc: 'handleLocalRefuse'
                },
                { // 新增全局拒绝规则
                    reg: /^#全局(一键拒绝|解除拒绝)$/i,
                    fnc: 'handleGlobalRefuse'
                },
                { // 功能开关（修改正则匹配规则）
                    reg: /^#(开启|关闭)\s*(强娶|离婚)(\s+(强娶|离婚))*$/i,
                    fnc: 'toggleFeature'
                }
            ]
        });

        // 每天凌晨4点重置临时数据
        schedule.scheduleJob('0 4 * * *', async () => {
            await this.clearTemporaryData();
        });
    }

    /** 随机选择CP */
    async chooseWife(e) {
        const groupId = e.group_id;
        const userId = e.user_id;

        // 检查今日是否已参与
        const usedKey = `RandomCP:TemporaryData:${groupId}:Used`;
        if (await redis.sIsMember(usedKey, userId.toString())) {
            return this.handleUsedUser(e);
        }

        // 获取随机群成员
        const randomWife = await this.getRandomMember(e);
        if (!randomWife) return;

        // 建立双向绑定关系
        await this.saveRelationship(groupId, e, randomWife);

        e.reply(this.buildMessage(
            userId,
            `你今天的群 CP 是`,
            randomWife.user_id,
            randomWife.nickname,
            `看好她哦，别让她乱跑~`
        ));
    }

    /** 处理离婚功能（带次数限制） */
    async handleDivorce(e) {
        const groupId = e.group_id;
        const userId = e.user_id;

        // 检查离婚功能状态
        const config = await this.getGroupConfig(groupId);
        if (config.divorce === '0') {
            return e.reply([segment.at(userId), "\n本群已禁用离婚功能~"]);
        }

        const usedKey = `RandomCP:TemporaryData:${groupId}:Used`;
        const divorceKey = `RandomCP:TemporaryData:${groupId}:DivorceCount`;

        // 检查离婚次数（每日最多3次）
        const divorceCount = parseInt(await redis.hGet(divorceKey, userId.toString())) || 0;
        if (divorceCount >= 3) {
            return e.reply([segment.at(userId), "\n今天已经离婚太多次啦，明天再来吧~"]);
        }

        // 检查是否已绑定CP
        if (!await redis.sIsMember(usedKey, userId.toString())) {
            return e.reply([segment.at(userId), "\n你还没有CP哦，暂时不能离婚呢~"]);
        }

        // 获取绑定关系数据
        const [activeData, passiveData] = await Promise.all([
            this.getRedisData(`RandomCP:TemporaryData:${groupId}:Active:${userId}`),
            this.getRedisData(`RandomCP:TemporaryData:${groupId}:Passive:${userId}`)
        ]);

        // 处理数据异常情况
        if (!activeData && !passiveData) {
            await redis.sRem(usedKey, userId.toString());
            return e.reply([segment.at(userId), "\n[系统异常] 你的CP数据不存在，已解除限制"]);
        }

        // 获取CP信息
        const cpInfo = activeData || passiveData;
        const cpId = cpInfo.id;
        const cpName = cpInfo.name;

        // 删除所有相关数据
        await Promise.all([
            redis.del(`RandomCP:TemporaryData:${groupId}:Active:${userId}`),
            redis.del(`RandomCP:TemporaryData:${groupId}:Passive:${cpId}`),
            redis.sRem(usedKey, userId.toString()),
            redis.sRem(usedKey, cpId.toString())
        ]);

        // 增加离婚次数
        await redis.hIncrBy(divorceKey, userId.toString(), 1);
        const remaining = 2 - divorceCount;

        e.reply([
            segment.at(userId),
            `\n你已与 `,
            segment.image(`https://q1.qlogo.cn/g?b=qq&s=0&nk=${cpId}`),
            `【${cpName}】(${cpId}) 解除CP关系（今日剩余离婚次数：${remaining}次）`
        ]);
    }

    /** 处理强制绑定 */
    async forceMarry(e) {
        const groupId = e.group_id;
        const userId = e.user_id;

        // 检查强娶功能状态
        const config = await this.getGroupConfig(groupId);
        if (config.forceMarry === '0') {
            return e.reply([segment.at(userId), "\n本群已禁用强娶功能~"]);
        }

        // 获取被@用户信息
        const atSegments = e.message.filter(msg => msg.type === 'at');
        if (atSegments.length === 0) {
            return e.reply("请@你想要指定的对象哦~");
        }

        // 解析目标用户ID并确保字符串类型
        const targetId = String(atSegments[0].qq);
        if (targetId === userId.toString()) {
            return e.reply("不能指定自己哦，要自攻自受吗？");
        }
        if (targetId === e.bot.uin.toString()) {
            return e.reply("机器人是不可以攻略的哦~");
        }

        // 获取群成员信息
        const memberMap = await e.group.getMemberMap();
        const targetMember = memberMap.get(parseInt(targetId));
        if (!targetMember) {
            return e.reply("该用户不在本群，无法指定~");
        }

        // 检查拒绝状态
        const [isGlobalRefuse, isLocalRefuse] = await Promise.all([
            redis.sIsMember('RandomCP:Config:Refuse', targetId),
            redis.sIsMember(`RandomCP:Config:${groupId}:Refuse`, targetId)
        ]);
        
        if (isGlobalRefuse || isLocalRefuse) {
            return e.reply([
                segment.at(userId),
                `\n⚠️ 对方已开启${isGlobalRefuse ? '全局' : '本群'}拒绝功能，无法指定~`
            ]);
        }

        // 检查双方状态
        const usedKey = `RandomCP:TemporaryData:${groupId}:Used`;
        const [isSelfUsed, isTargetUsed] = await Promise.all([
            redis.sIsMember(usedKey, userId.toString()),
            redis.sIsMember(usedKey, targetId)
        ]);

        if (isSelfUsed || isTargetUsed) {
            return e.reply(isSelfUsed ? "你今天已经有CP了哦~" : "对方已经被抢走了，来晚一步啦~");
        }

        // 建立强制绑定关系
        await this.saveRelationship(groupId, e, targetMember);

        e.reply(this.buildMessage(
            userId,
            `你成功指定CP啦`,
            targetMember.user_id,
            targetMember.nickname,
            `现在开始TA就是你的专属CP啦~`
        ));
    }

    /** 处理本地拒绝功能 */
    async handleLocalRefuse(e) {
        const groupId = e.group_id;
        const userId = e.user_id.toString();
        const command = e.msg.match(/^#(一键拒绝|解除拒绝)$/i)[1].toLowerCase();

        const refuseKey = `RandomCP:Config:${groupId}:Refuse`;
        
        if (command === '一键拒绝') {
            await redis.sAdd(refuseKey, userId);
            return e.reply([segment.at(userId), "\n✅ 你已开启本群拒绝功能"]);
        } else {
            await redis.sRem(refuseKey, userId);
            return e.reply([segment.at(userId), "\n✅ 你已解除本群拒绝状态"]);
        }
    }

    /** 处理全局拒绝功能 */
    async handleGlobalRefuse(e) {
        const userId = e.user_id.toString();
        const command = e.msg.match(/^#全局(一键拒绝|解除拒绝)$/i)[1].toLowerCase();

        const globalKey = 'RandomCP:Config:Refuse';
        
        if (command === '一键拒绝') {
            await redis.sAdd(globalKey, userId);
            return e.reply([segment.at(userId), "\n🌍 你已开启全局拒绝功能"]);
        } else {
            await redis.sRem(globalKey, userId);
            return e.reply([segment.at(userId), "\n🌍 你已解除全局拒绝状态"]);
        }
    }

    /** 功能开关控制 */
    async toggleFeature(e) {
        if (!e.isMaster) {
            return e.reply("只有主人才能使用该命令哦~");
        }

        const groupId = e.group_id;
        if (!groupId) {
            return e.reply("请在群聊中使用该命令~");
        }

        // 使用更可靠的参数解析方式
        const operationMatch = e.msg.match(/^#(开启|关闭)/i);
        if (!operationMatch) return;
        
        const operation = operationMatch[1];
        const featuresPart = e.msg.slice(operationMatch[0].length).trim();
        const features = featuresPart.split(/\s+/).filter(f => ['强娶', '离婚'].includes(f));

        if (features.length === 0) {
            return e.reply("请指定要操作的功能（强娶/离婚）~");
        }

        const configKey = `RandomCP:Config:${groupId}`;
        const config = await redis.hGetAll(configKey) || {};

        // 逐个更新功能状态
        for (const feature of features) {
            const field = feature === '强娶' ? 'forceMarry' : 'divorce';
            config[field] = operation === '开启' ? '1' : '0';
        }

        // 批量更新Redis配置
        await redis.hSet(configKey, config);
        e.reply(`已成功${operation === '开启' ? '启用' : '禁用'}功能：${features.join(', ')}`);
    }

    /** 处理已绑定用户状态查询 */
    async handleUsedUser(e) {
        const groupId = e.group_id;
        const userId = e.user_id;
        
        const activeData = await this.getRedisData(`RandomCP:TemporaryData:${groupId}:Active:${userId}`);
        if (activeData) {
            return e.reply(this.buildMessage(
                userId,
                `你今天已经有CP了哦~`,
                activeData.id,
                activeData.name,
                "不许三心二意了哦~"
            ));
        }

        const passiveData = await this.getRedisData(`RandomCP:TemporaryData:${groupId}:Passive:${userId}`);
        if (passiveData) {
            return e.reply(this.buildMessage(
                userId,
                `你今天已经被TA娶走了哦~`,
                passiveData.id,
                passiveData.name,
                "乖乖的不要乱跑哦~"
            ));
        }

        const usedKey = `RandomCP:TemporaryData:${groupId}:Used`;
        await redis.sRem(usedKey, userId.toString());
        e.reply(`[系统异常] 状态数据错误，已重置你的限制`);
    }

    /** 构建消息模板 */
    buildMessage(userId, text, qq, name, suffix) {
        return [
            segment.at(userId),
            `\n${text}`,
            segment.image(`https://q1.qlogo.cn/g?b=qq&s=0&nk=${qq}`),
            `【${name}】(${qq})\n${suffix}`
        ];
    }

    /** 获取随机群成员 */
    async getRandomMember(e) {
        const groupId = e.group_id;
        const userId = e.user_id;
        
        const mmap = await e.group.getMemberMap();
        const members = Array.from(mmap.values());

        // 获取拒绝列表
        const [usedMembers, refuseMembers] = await Promise.all([
            redis.sMembers(`RandomCP:TemporaryData:${groupId}:Used`),
            redis.sMembers(`RandomCP:Config:${groupId}:Refuse`)
        ]);

        const usedIds = new Set(usedMembers.map(Number));
        const refuseIds = new Set(refuseMembers.map(Number));

        // 过滤拒绝用户
        const available = members.filter(m => 
            m.user_id !== userId &&
            m.user_id !== e.bot.uin &&
            !usedIds.has(m.user_id) &&
            !refuseIds.has(m.user_id)
        );

        if (available.length === 0) {
            e.reply('今日没有可选的CP对象了~');
            return null;
        }

        return available[Math.floor(Math.random() * available.length)];
    }

    /** 保存关系数据 */
    async saveRelationship(groupId, e, target) {
        const usedKey = `RandomCP:TemporaryData:${groupId}:Used`;
        
        await redis.sAdd(usedKey, [e.user_id.toString(), target.user_id.toString()]);

        await Promise.all([
            this.setRedisData(
                `RandomCP:TemporaryData:${groupId}:Active:${e.user_id}`,
                { id: target.user_id, name: target.nickname }
            ),
            this.setRedisData(
                `RandomCP:TemporaryData:${groupId}:Passive:${target.user_id}`,
                { id: e.user_id, name: e.nickname }
            )
        ]);
    }

    /** 清空临时数据 */
    async clearTemporaryData() {
        const keys = await redis.keys('RandomCP:TemporaryData:*');
        if (keys.length) await redis.del(keys);
    }

    /** 获取群组配置 */
    async getGroupConfig(groupId) {
        const config = await redis.hGetAll(`RandomCP:Config:${groupId}`) || {};
        return {
            forceMarry: config.forceMarry ?? '1',
            divorce: config.divorce ?? '1'
        };
    }

    /** Redis数据存取 */
    async getRedisData(key) {
        const data = await redis.get(key);
        return data ? JSON.parse(data) : null;
    }
    async setRedisData(key, value) {
        await redis.set(key, JSON.stringify(value));
    }
}
